package com.tl.sun.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.google.gson.Gson;
import com.liaoinstan.springview.container.DefaultFooter;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.request.BaseRequest;
import com.tl.sun.AppContext;
import com.tl.sun.OkHeader;
import com.tl.sun.R;
import com.tl.sun.event.AdapterEvent;
import com.tl.sun.model.ChildMsg;
import com.tl.sun.model.Level0Item;
import com.tl.sun.model.SystemMsgBean;
import com.tl.sun.ui.adapter.SystemMsgAdapter;
import com.tl.sun.utils.ToastUtil;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class SystemMsgActivity extends BaseActivity {

    @Bind(R.id.tv_generic_title)
    TextView mTvGenericTitle;
    @Bind(R.id.tv_set_read)
    TextView mTvSetRead;
    @Bind(R.id.tv_message_null)
    TextView mTvMessageNull;
    @Bind(R.id.rl_generic_back)
    RelativeLayout mRelativeLayout;
    @Bind(R.id.recycleview)
    RecyclerView mRecycleview;
    @Bind(R.id.springView)
    SpringView mSpringView;

    private int page = 1;
    private ArrayList<MultiItemEntity> mData;
    private ArrayList<MultiItemEntity> mFinalData = new ArrayList<>();
    private SystemMsgAdapter mAdapter;


    public static Intent newIntent() {
        Intent intent = new Intent();
        intent.setClass(AppContext.getInstance(), SystemMsgActivity.class);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_system_msg);
        ButterKnife.bind(this);
        init();
        initListener();
        // getMessageByNet(page);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // page = 1;
        getMessageByNet(page);
    }

    private void initListener() {
        mRelativeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mSpringView.setType(SpringView.Type.FOLLOW);
        mSpringView.setHeader(new DefaultHeader(this));
        mSpringView.setFooter(new DefaultFooter(this));
        mSpringView.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                mFinalData.clear();
                getMessageByNet(page);
            }

            @Override
            public void onLoadmore() {
                getMessageByNet(page);
            }
        });
    }

    /**
     * 获取网络消息
     *
     * @param page
     */
    private void getMessageByNet(final int page) {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(this))
                .post(AppContext.getInstance().getBaseUrl() + "ucenter/msg_list")
//                .params("page", page)
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);

                        mData.clear();
                        mFinalData.clear();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        mSpringView.onFinishFreshAndLoad();
                        try {
                            JSONObject jo = new JSONObject(s);
                            String ret = jo.getString("ret");
                            String code = jo.getString("code");
                            String msg = jo.getString("msg");
                            if (ret.equals("0") && code.equals("1")) {
                                SystemMsgBean msgBean = new Gson().fromJson(s, SystemMsgBean.class);
                                List<SystemMsgBean.RetDataBean> retData = msgBean.getRet_data();
                                if (retData.size() == 0 && page == 1) {
                                    ToastUtil.showToast("无数据");
                                    mTvMessageNull.setVisibility(View.VISIBLE);
                                    mRecycleview.setVisibility(View.GONE);
                                    return;
                                }
                                mTvMessageNull.setVisibility(View.GONE);
                                mRecycleview.setVisibility(View.VISIBLE);
                                updateData(retData);
                            } else if (ret.equals("0") && code.equals("2")) {
                                mTvMessageNull.setVisibility(View.VISIBLE);
                                mRecycleview.setVisibility(View.GONE);
                            }
                        } catch (Exception e) {
                        }
                    }
                });
    }

    private void updateData(List<SystemMsgBean.RetDataBean> retData) {
        page++;
        if (page >= 2 && retData.size() > 0) {
            for (int i = 0; i < retData.size(); i++) {
                Level0Item father = new Level0Item();
                father.setId(retData.get(i).getMsg_id());
                father.setTitle(retData.get(i).getTitle());
                father.setContent(retData.get(i).getContent());
                father.setReadFlag(retData.get(i).getReadFlag());
                father.setSend_date(retData.get(i).getSend_date());
                ChildMsg childMsg = new ChildMsg();
                childMsg.setMsgId(retData.get(i).getMsg_id());
                childMsg.setTitle(retData.get(i).getTitle());
                childMsg.setContent(retData.get(i).getContent());
                childMsg.setRead_flag(retData.get(i).getReadFlag());
                childMsg.setSend_date(retData.get(i).getSend_date());
                father.addSubItem(childMsg);
                mData.add(father);
            }

            for (MultiItemEntity a : mData) {
                mFinalData.add(a);
            }

            mAdapter.notifyDataSetChanged();

        } else if (page >= 2 && retData.size() <= 0) {
            page--;
            //  ToastUtils.showShortToast("没有更多数据了");
        }

    }

    private void init() {
        mTvGenericTitle.setText("系统消息");
        mData = new ArrayList<>();
        mRecycleview.setLayoutManager(new LinearLayoutManager(this));

        mAdapter = new SystemMsgAdapter(mFinalData);
        mRecycleview.setAdapter(mAdapter);

    }

    @OnClick(R.id.tv_set_read)
    public void onClick() {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(this))
                .post(AppContext.getInstance().getBaseUrl() + "ucenter/read_flag")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Logger.e(s);
                        try {
                            JSONObject jo = new JSONObject(s);
                            String ret = jo.getString("ret");
                            String code = jo.getString("code");
                            String msg = jo.getString("msg");
                            if (ret.equals("0") && code.equals("1")) {
                                ToastUtil.showToast("标记已读成功");
//                                mAdapter.notifyDataSetChanged();
                                page--;
                                getMessageByNet(page);
                            } else if (ret.equals("1") && code.equals("-1")) {
                                // ToastUtil.showToast("标记已读失败");
                            }
                        } catch (Exception e) {
                        }
                    }
                });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AdapterEvent event) {
        Level0Item father = event.getFather();
        int pos = event.getPos();
        setRead(father, pos);
    }

    private void setRead(final Level0Item father, final int pos) {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(this))
                .post(AppContext.getInstance().getBaseUrl() + "ucenter/read_flag")
                .params("msg_id", father.getId())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Logger.e(s);
                        try {
                            JSONObject jo = new JSONObject(s);
                            String ret = jo.getString("ret");
                            String code = jo.getString("code");
                            String msg = jo.getString("msg");
                            if (ret.equals("0") && code.equals("1")) {
                                ChildMsg subItem = father.getSubItem(pos);
                                father.setReadFlag("1");
                                subItem.setRead_flag("1");
                                mAdapter.notifyDataSetChanged();
                            } else if (ret.equals("1") && code.equals("-1")) {
                                // ToastUtil.showToast("标记已读失败");
                            }
                        } catch (Exception e) {
                        }
                    }
                });
    }
}
